package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.common.constants.ArticleBehaviorConstants;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.UserRelationDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApFollowBehaviorService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * ClassName: ApLikeBehaviorServiceImpl
 * Description:
 * date: 2023/8/27 0027 16:33
 *
 * @author zHan
 */
@Service
@Slf4j
public class ApFollowBehaviorServiceImpl implements ApFollowBehaviorService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private ApUserFollowMapper apUserFollowMapper;

    @Autowired
    private ApUserFanMapper apUserFanMapper;

    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * 关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult userFollow(UserRelationDto dto) {
        checkParam(dto);
        // 获取用户id
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 定义key
        String followKey = ArticleBehaviorConstants.FOLLOW + user.getId()
                + ":" + dto.getAuthorId();
        // 如果为0，关注
        if (dto.getOperation() == 0) {
            dto.setArticleId(null);
            String value = JSON.toJSONString(dto);
            cacheService.set(followKey, value);
            // 新增用户关注
            addDbFollow(dto, user);
            // 新增用户粉丝
            addDbFan(dto, user);
        } else {
            // 取消关注
            apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                    .eq(ApUserFollow::getUserId, user.getId())
                    .eq(ApUserFollow::getFollowId, dto.getAuthorId()));
            apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getUserId, dto.getAuthorId())
                    .eq(ApUserFan::getFansId, user.getId()));
            cacheService.delete(followKey);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 新增用户粉丝
     * @param dto
     * @param user
     */
    private void addDbFan(UserRelationDto dto, ApUser user) {
        ApUser apUser = apUserMapper.selectById(user.getId());
        ApUserFan apUserFan = new ApUserFan(dto.getAuthorId(), user.getId(), apUser.getName()
                , new Date());
        // 新增数据
        apUserFanMapper.insert(apUserFan);
    }

    /**
     * 新增用户关注
     * @param dto
     * @param user
     */
    private void addDbFollow(UserRelationDto dto, ApUser user) {
        // 查询自媒体昵称
        ResponseResult responseResult = wemediaClient.getWmUser(dto.getAuthorId());
        if (responseResult.getCode().equals(200)) {
            String jsonWmUser = JSON.toJSONString(responseResult.getData());
            WmUser wmUser = JSON.parseObject(jsonWmUser, WmUser.class);
            if (wmUser == null) {
                throw new CustomException(AppHttpCodeEnum.WM_USER_DATA_NOT_EXIST);
            }
            // 用户关注
            ApUserFollow apUserFollow = ApUserFollow.builder()
                    .userId(user.getId())
                    .followId(dto.getAuthorId())
                    .followName(wmUser.getNickname())
                    .createdTime(new Date())
                    .level((short) 0)
                    .isNotice((short) 0).build();
            // 新增数据
            apUserFollowMapper.insert(apUserFollow);
        }
    }

    /**
     * 检查参数
     *
     * @param dto
     */
    private void checkParam(UserRelationDto dto) {
        // 检查参数
        if (dto.getArticleId() == null || dto.getAuthorId() == null || dto.getOperation() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getOperation() < 0 || dto.getOperation() > 1) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
    }
}
